package com.example.star.adapter;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide; // 用于加载图片
import com.example.star.entity.Message;
import com.example.star.R;

import java.util.List;

public class MessageAdapter extends BaseAdapter {

    private Context mContext;
    private List<Message> messageList;
    private String userName;

    public MessageAdapter(Context mContext, List<Message> messageList) {
        this.mContext = mContext;
        this.messageList = messageList;
    }

    @Override
    public int getCount() {
        return messageList.size();
    }

    @Override
    public Object getItem(int position) {
        return messageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_message, parent, false);
        } else {
            view = convertView;
        }

        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", "");

        Message message = messageList.get(position);
        ImageView messageImage = view.findViewById(R.id.image_message);
        TextView usernameTextView = view.findViewById(R.id.username);
        TextView messageTextView = view.findViewById(R.id.text_message);

        // 显示消息内容
        messageTextView.setText(message.getMessage());
        usernameTextView.setText(message.getUserName());

        // 显示用户头像
        if (message.getUser() != null && message.getUser().getAvatar() != null) {
            //获取图片
            Glide.with(mContext)
                    .load(message.getUser().getAvatar())
                    .placeholder(R.drawable.register)
                    .error(R.drawable.register)
                    .into(messageImage);
        }

        // 增加空值检查
        if (message.getUserName() != null && message.getUserName().equals(userName)) {
            // 登录用户的消息在右边
            view.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        } else {
            // 其他用户的消息在左边
            view.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
        }
        return view;
    }
}